package controllers;

import bill.Bill;
import enums.BillOutStatus;
import enums.BillStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import models.weixin.amount.WebUserAccount;
import order.OrderItem;
import play.Logger;
import play.mvc.Controller;
import play.mvc.With;
import util.common.DateUtil;

import java.util.*;

/**
 * 财务管理
 * Created by youliangcheng on 17/6/28.
 */
@With(LoginInCtrl.class)
public class FinanceCtrl extends Controller {

    public static void index(){
        Merchant merchant = LoginInCtrl.getMerchant();
        WebUser user = new WebUser();
        if(merchant.webUserId !=null){
            user = WebUser.findByUserId(merchant.webUserId);
        }

        //判断是否可以提现,目前暂定只有webUser本人登录时才可以提现
        boolean canWthDrawal = true;
        if(user != null && user.id != null )
            canWthDrawal = true;
        render(user , canWthDrawal);
    }


    //提现 withdrawal : [wɪð'drɔː(ə)l]
    public static void withDrawal(){
        Merchant merchant = LoginInCtrl.getMerchant();
        //        Merchant merchant = Merchant.findByMerchantId(1);
        WebUser webUser = WebUser.findByUserId(merchant.webUserId);
        WebUserAccount webUserAccount = WebUserAccount.findByWebUser(webUser);
        render(webUserAccount);
    }

    //财务信息
    public static void financeInfo(){
        Merchant merchant = LoginInCtrl.getMerchant();
        //默认展示近一个月的资金流水
        Date nowTime = new Date();
        String beginDate = DateUtil.dateToString(DateUtil.getDateForLastMonth(nowTime) , "yyyy-MM-dd");
        String endDate = DateUtil.dateToString(nowTime , "yyyy-MM-dd");
        render(beginDate ,endDate);
    }

    public static void getAccounts(String beginDate , String endDate){
        Logger.info("beginDate=========== :%s",beginDate);
        Logger.info("endDate=========== :%s",endDate);
        Merchant merchant = LoginInCtrl.getMerchant();
        Map<String,Object> resultMap = new HashMap<>();
        String newEndDate =endDate+" 23:59:59";
        List<Bill> billList = Bill.getBillListByDate(merchant, BillOutStatus.NORMAL, BillStatus.IN_AMOUNT,beginDate,newEndDate);
        Logger.info("billList ============== :%s",billList.size());
        List<Bill> bills = new ArrayList<>();
        for(Bill bill : billList){
            bill.createAtStr = DateUtil.dateToString(bill.createAt , "yyyy-MM-dd");
            Logger.info("bill.createAtStr=========== :%s",bill.createAtStr);
            bills.add(bill);
        }
        List<Map<String , Object>> sumMoney = Bill.getBillSumMoneyByDate(merchant.id, BillOutStatus.NORMAL, BillStatus.IN_AMOUNT,beginDate,newEndDate);
        resultMap.put("sumMoney",sumMoney.get(0).get("sumMoney"));


        resultMap.put("billList",bills);
        renderJSON(resultMap);
    }


    public static void orderDetails(long orderId){
        OrderItem orderItem = null;
        orderItem = OrderItem.findByOrderId(orderId);
        render(orderItem);

    }

}
